package org.byqh.dqeai.controller.custom;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.common.UdpMessage;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * @author ShouWang
 */
@RestController
@RequestMapping("/protocol-forwarding")
@Validated
@Tag(name = "自定义 - 动态数据接口")
public class ProtocolForwardingController {

    @PostMapping(value = "/to-udp")
    public Json toUdp(@RequestBody(required = true) UdpMessage msg) throws ResponseStatusException {

        InetSocketAddress inetSocketAddress = new InetSocketAddress(msg.getIp(), msg.getPort());
        byte[] udpMessage = msg.getMessage().getBytes();
        DatagramPacket datagramPacket = null;
        try (DatagramSocket datagramSocket = new DatagramSocket()) {
            datagramPacket = new DatagramPacket(udpMessage, udpMessage.length, inetSocketAddress);
            datagramSocket.send(datagramPacket);
        } catch (IOException e) {
            return Json.success(e.getMessage());
        }
        return Json.success("");
    }
}
